define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    var newhouse_id = Fast.api.query('newhouse_id');
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'newhouse/structure/index' + location.search,
                    add_url: 'newhouse/structure/add',
                    edit_url: 'newhouse/structure/edit',
                    del_url: 'newhouse/structure/del',
                    multi_url: 'newhouse/structure/multi',
                    table: 'newhouse_structure',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                queryParams: function (params) {
                    var filter = params.filter ? JSON.parse(params.filter) : {};
                    var op = params.op ? JSON.parse(params.op) : {};

                    if (newhouse_id) {
                        filter['newhouse_id'] = newhouse_id;
                    }
                    params.filter = JSON.stringify(filter);
                    return params;
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'newhousecategory.name', title: __('Newhousecategory.name')},
                        {field: 'title', title: __('Title')},
                        {field: 'flag', title: __('Flag'), searchList: {"0":__('Flag 0'),"1":__('Flag 1')}, formatter: Controller.api.formatter.flag},
                        {field: 'price', title: __('Price'), searchList: {"0":__('Price 0'),"1":__('Price 1')}, formatter: Controller.api.formatter.price},
                        {field: 'status', title: __('Status'), searchList: {"0":__('Status 0'),"1":__('Status 1'),"2":__('Status 2'),"3":__('Status 3')}, formatter: Table.api.formatter.normal},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, buttons: [
                                {
                                    name: 'ld',
                                    text: '楼栋构成',
                                    icon: 'fa fa-building',
                                    classname: 'btn btn-xs btn-default btn-addtabs',
                                    url: function (row, column) {
                                        return "newhouse/building?newhouse_id=" + newhouse_id + "&structure_id=" + row.id;
                                    }
                                }], events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ],
                search: true,//newhouse_id?false:true,
                commonSearch: true //newhouse_id?false:true
            });

            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                if (newhouse_id) {
                    $(".columns-right").hide();
                } else {
                    $(".btn-add").hide();
                }
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            $(".btn-add").data("area", ["90%", "90%"]);
            $(".btn-edit").data("area", ["90%", "90%"]);
            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone").data("area", ["90%", "90%"]);
            });

            var parenttable = table.closest('.bootstrap-table');
            var options = table.bootstrapTable('getOptions');
            var toolbar = $(options.toolbar, parenttable);
            $(toolbar).off('click', Table.config.addbtn);
            $(toolbar).on('click', Table.config.addbtn, function () {
                var ids = Table.api.selectedids(table);
                var url = options.extend.add_url;
                if (url.indexOf("{ids}") !== -1) {
                    url = Table.api.replaceurl(url, {ids: ids.length > 0 ? ids.join(",") : 0}, table);
                }
                if (newhouse_id !== null) {
                    url = url + '?newhouse_id=' + newhouse_id;
                }
                Fast.api.open(url, __('Add'), $(this).data() || {});
            });
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'newhouse/structure/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'newhouse/structure/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'newhouse/structure/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            if (newhouse_id) {
                $('#c-newhouse_id').val(newhouse_id);
            }
            $("#c-category_id").data("params", function (obj) {
                return {custom: {newhouse_id: newhouse_id}};
            });
            $("#c-category_id").data("eSelect", function () {
                $("#c-salelabel_ids").val('');
                $("#c-salelabel_ids").parent().find(".selected_tag").remove();
            });

            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));

                var cover_image_input = $('#plupload-cover_image').data("input-id") ? $('#plupload-cover_image').data("input-id") : "";
                var cover_image_preview = $('#plupload-cover_image').data("preview-id") ? $('#plupload-cover_image').data("preview-id") : "";
                if (cover_image_preview) {
                    $(document.body).off("click", "#" + cover_image_preview + " .btn-trash");
                    // 监听事件
                    $("#plupload-cover_image").data("upload-success", function(data, ret) {
                        //这里进行后续操作
                        $(this).hide();
                    });
                    // 移除按钮事件
                    $(document.body).on("click", "#" + cover_image_preview + " .btn-trash", function () {
                        var that = $(this);
                        var path = $("#" + cover_image_preview + " [data-url]");
                        Layer.confirm('是否删除该图片？（删除后不可恢复）',
                            {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
                            function (index) {
                                var options = {
                                    url: 'newhouse/structure/delUpload',
                                    data: {
                                        sid: $("#plupload-cover_image").data('sid'),
                                        dbfield: $("#plupload-cover_image").data('field'),
                                        path: path.data("url")
                                    }
                                }
                                Fast.api.ajax(options, function () {
                                    $("#" + cover_image_input).val('');
                                    that.closest("li").remove();
                                    $("#plupload-cover_image").show();
                                    Layer.close(index);
                                });
                            }
                        );
                    });
                }
                if ($("#" + cover_image_input).val() != '') {
                    $("#" + cover_image_input).hide();
                }

                var view3d_image_input = $('#plupload-3d_image').data("input-id") ? $('#plupload-3d_image').data("input-id") : "";
                var view3d_image_preview = $('#plupload-3d_image').data("preview-id") ? $('#plupload-3d_image').data("preview-id") : "";
                if (view3d_image_preview) {
                    $(document.body).off("click", "#" + view3d_image_preview + " .btn-trash");
                    // 监听事件
                    $("#plupload-3d_image").data("upload-success", function(data, ret) {
                        //这里进行后续操作
                        $(this).hide();
                    });
                    // 移除按钮事件
                    $(document.body).on("click", "#" + view3d_image_preview + " .btn-trash", function () {
                        var that = $(this);
                        var path = $("#" + view3d_image_preview + " [data-url]");
                        Layer.confirm('是否删除该图片？（删除后不可恢复）',
                            {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
                            function (index) {
                                var options = {
                                    url: 'newhouse/structure/delUpload',
                                    data: {
                                        sid: $("#plupload-3d_image").data('sid'),
                                        dbfield: $("#plupload-3d_image").data('field'),
                                        path: path.data("url")
                                    }
                                }
                                Fast.api.ajax(options, function () {
                                    $("#" + view3d_image_input).val('');
                                    that.closest("li").remove();
                                    $("#plupload-3d_image").show();
                                    Layer.close(index);
                                });
                            }
                        );
                    });
                }
                if ($("#" + view3d_image_input).val() != '') {
                    $("#" + view3d_image_input).hide();
                }

                var video_image_input = $('#plupload-video_image').data("input-id") ? $('#plupload-video_image').data("input-id") : "";
                var video_image_preview = $('#plupload-video_image').data("preview-id") ? $('#plupload-video_image').data("preview-id") : "";
                if (video_image_preview) {
                    $(document.body).off("click", "#" + video_image_preview + " .btn-trash");
                    // 监听事件
                    $("#plupload-video_image").data("upload-success", function(data, ret) {
                        //这里进行后续操作
                        $(this).hide();
                    });
                    // 移除按钮事件
                    $(document.body).on("click", "#" + video_image_preview + " .btn-trash", function () {
                        var that = $(this);
                        var path = $("#" + video_image_preview + " [data-url]");
                        Layer.confirm('是否删除该图片？（删除后不可恢复）',
                            {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
                            function (index) {
                                var options = {
                                    url: 'newhouse/structure/delUpload',
                                    data: {
                                        sid: $("#plupload-video_image").data('sid'),
                                        dbfield: $("#plupload-video_image").data('field'),
                                        path: path.data("url")
                                    }
                                }
                                Fast.api.ajax(options, function () {
                                    $("#" + video_image_input).val('');
                                    that.closest("li").remove();
                                    $("#plupload-video_image").show();
                                    Layer.close(index);
                                });
                            }
                        );
                    });
                }
                if ($("#" + video_image_input).val() != '') {
                    $("#" + video_image_input).hide();
                }

                $("#c-salelabel_ids").data("params", function () {
                    var param = '';
                    switch($("#c-category_id").val()) {
                        case '1':
                        case '5':
                            param = 1;
                            break;
                        case '2':
                        case '3':
                        case '4':
                            param = 3;
                            break;
                    }
                    return {custom: {type: param}};
                });
            },
            formatter: {
                flag: function (value, row, index) {
                    return '<a class="btn-change text-success" data-url="'+$.fn.bootstrapTable.defaults.extend.multi_url+'" data-id="' + row.id + '" data-params="flag=' + (row.flag == '0' ? '1' : '0') + '"><i class="fa ' + (row.flag == '0' ? 'fa-toggle-off' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
                price: function (value, row, index) {
                    return '<a class="btn-change text-success" data-url="'+$.fn.bootstrapTable.defaults.extend.multi_url+'" data-id="' + row.id + '" data-params="price=' + (row.price == '0' ? '1' : '0') + '"><i class="fa ' + (row.price == '0' ? 'fa-toggle-off' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                }
            }
        }
    };
    return Controller;
});
